package net;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * TCP网络编程-服务端
 * (字符流)
 */
public class SocketTCP03Server {

    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("等待客户端请求...");
        Socket socket = serverSocket.accept();
        System.out.println(socket.getClass());

        OutputStream outputStream = socket.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String str = bufferedReader.readLine();
        System.out.println(str);

        if (str.equals("hello, server 字符流")) {
            System.out.println("接收到客户端请求:" + str);
            bufferedWriter.write("hello, client 字符流");
            bufferedWriter.newLine();
            bufferedWriter.flush(); //使用writer需要手动刷新
            //设置写入结束标记
//            socket.shutdownOutput();
            System.out.println("服务端退出...");
            inputStream.close();
            socket.close();
            outputStream.close();
            serverSocket.close();
        }
    }
}
